<?php
header('Content-Type: application/json');

// Database configuration - same as your original file
define('DB_HOST', 'localhost');
define('DB_NAME', 'music_db');
define('DB_USER', '73327382');
define('DB_PASS', '73327382');

// Security measure - require a confirmation parameter
$confirm = filter_input(INPUT_GET, 'confirm', FILTER_SANITIZE_STRING) ?? '';

try {
    // Create database connection
    $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4";
    $pdo = new PDO($dsn, DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Only proceed if confirmation is provided
    if ($confirm !== 'DELETE_ALL') {
        throw new Exception("Confirmation required. Add ?confirm=DELETE_ALL to the URL to proceed.");
    }
    
    // Get all tables in the database
    $stmt = $pdo->query("SHOW TABLES");
    $tables = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    if (empty($tables)) {
        throw new Exception("No tables found in the database.");
    }
    
    // Disable foreign key checks temporarily
    $pdo->exec("SET FOREIGN_KEY_CHECKS = 0");
    
    $deletedTables = [];
    $totalRowsDeleted = 0;
    
    // Truncate each table (this is faster than DELETE and resets auto-increment)
    foreach ($tables as $table) {
        $stmt = $pdo->prepare("TRUNCATE TABLE `$table`");
        $stmt->execute();
        
        // Get row count (for information purposes)
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM `$table`");
        $stmt->execute();
        $count = $stmt->fetchColumn();
        
        $deletedTables[] = [
            'table' => $table,
            'rows_before' => $count, // Should be 0 after truncate
        ];
    }
    
    // Re-enable foreign key checks
    $pdo->exec("SET FOREIGN_KEY_CHECKS = 1");
    
    // Build response
    $response = [
        'status' => 'success',
        'message' => 'All tables have been truncated.',
        'tables_affected' => $deletedTables,
        'total_tables' => count($tables)
    ];
    
    echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

} catch (PDOException $e) {
    // Database error handling
    http_response_code(500);
    echo json_encode([
        'status' => 'error',
        'message' => 'Database error: ' . $e->getMessage(),
        'tables_affected' => [],
        'total_tables' => 0
    ]);
} catch (Exception $e) {
    // Other error handling
    http_response_code(400);
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage(),
        'tables_affected' => [],
        'total_tables' => 0
    ]);
}
?>